package com.wink.cachedemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

/**
 * @author xw
 * @date 2020-10-28 13:38
 */
@Slf4j
@Component
public class RedisListener extends MessageListenerAdapter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("redis订阅者收到消息！");
        log.info("thread-》{}",Thread.currentThread().getName());
        log.info("redis监听-消息内容-> {},thread:{}", message.toString(),Thread.currentThread().getName());
        // 请使用valueSerializer
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String topic = redisTemplate.getStringSerializer().deserialize(channel);
        Object msg = redisTemplate.getValueSerializer().deserialize(body);

        //  TODO: 2020/10/28 WINK 可以判断不同的topic（channel）分别处理
        log.info("channel:{}", topic);
        log.info("msg:{}", msg);
        log.info("redis订阅者消费消息完成！");
    }

    @Override
    protected void handleListenerException(Throwable ex) {
        log.error("Listener execution failed", ex);
    }
}
